﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SharpCompress.Archives;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using WorkFlowCore.Common.SimplePluginLoaders;
using WorkFlowCore.Workflows;

namespace WorkFlowCore.Plugins
{
    public class PluginManager:IDomainService
    {
        private readonly IBasicRepository<PluginInfo, Guid> pluginRepository;
        private readonly IBasicRepository<PluginApplyConfig, Guid> applyConfigRepository;
        private readonly IOptions<PluginOptions> pluginOptions;
        private readonly ILogger<PluginManager> logger;

        public PluginManager(IBasicRepository<PluginInfo, Guid> pluginRepository, IBasicRepository<PluginApplyConfig, Guid> applyConfigRepository, IOptions<PluginOptions> pluginOptions, ILogger<PluginManager> logger)
        {
            this.pluginRepository = pluginRepository;
            this.applyConfigRepository = applyConfigRepository;
            this.pluginOptions = pluginOptions;
            this.logger = logger;
        }


        public async Task AddPlugin(Plugin plugin,Stream pluginPackage)
        {

            var path = plugin.GetFilePath(pluginOptions.Value.BasePath);
            var dir = Path.GetDirectoryName(path);

            //如果目录已存在则删除
            if(Directory.Exists(dir))
            {
                UnloadPlugin(dir);
            }

            Directory.CreateDirectory(path);

            pluginPackage.Position = 0;
            //解压文件
            var archive = ArchiveFactory.Open(pluginPackage);
            foreach (var entry in archive.Entries)
            {
                if (!entry.IsDirectory)
                {
                    Console.WriteLine(entry.Key);
                    entry.WriteToDirectory(path, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
                }
            }

            await pluginRepository.InsertAsync(plugin.ToPluginInfo());

            SimplePluginLoader.LoadPlugins<ManifestWithConfig>(Directory.GetParent(path).FullName, null);
        }

        /// <summary>
        /// 卸载已经载入的插件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="entry"></param>
        private void UnloadPlugin(string entryPath)
        {
            try
            {
                var context = new PluginAssemblyLoadContext(System.IO.Path.Combine(entryPath));
                context.Unload();
                Directory.Delete(Path.GetDirectoryName(entryPath), true);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
            }
        }

        public async Task RemovePlugin(Guid id)
        {
            var pluginInfo = await pluginRepository.GetAsync(id);
            var plugin = pluginInfo.ToPlugin();
            var path = plugin.GetFilePath(pluginOptions.Value.BasePath);
            UnloadPlugin(path);
            await pluginRepository.DeleteAsync(id);

        }

    }
}
